#include "XFile.h"
#include "Mesh.h"
#include "../graphics/Graphics.h"

namespace leo {


XFile::XFile(Graphics& _graphics)
:
graphics(_graphics)
{
}
XFile::~XFile()
{
}



bool XFile::LoadMesh(Mesh& _Mesh, const std::string& _Filename)
{
	fileName = _Filename;  

	LPD3DXMESH mesh;

	HRESULT hr = D3DXLoadMeshFromX(fileName.c_str(),
									  D3DXMESH_SYSTEMMEM,
									  graphics.GetDevice(),
									  NULL,
									  NULL,
									  NULL,
									  NULL,
									  &mesh);

	if(hr != D3D_OK)
		return false;

	//-----------------------------------------------------------
	// Load vertex buffer

	LPDIRECT3DVERTEXBUFFER9 dxVB;
	mesh->GetVertexBuffer(&dxVB);

	// get vertex info
	DWORD nNumVerts = mesh->GetNumVertices();
	DWORD nSizeVerts = mesh->GetNumBytesPerVertex();
	
	// create vertex buffer
	VertexBuffer<TextureVertex, TEXTURE_VERTEX>::Ptr vb( 
								new VertexBuffer<TextureVertex, TEXTURE_VERTEX>(nNumVerts)
	);

	// get DX vertex data pointer
	void* pTemp = NULL;
	mesh->LockVertexBuffer(0, &pTemp);

	// 
	TextureVertex* pVertexData = vb->GetVerticesPtr();
	memcpy(static_cast<void*>(pVertexData), pTemp, nSizeVerts * nNumVerts);

	mesh->UnlockVertexBuffer();

	// assign VB to mesh
	_Mesh.SetVertexBuffer(vb);
	
//-----------------------------------
//------Load Index Buffer
	LPDIRECT3DINDEXBUFFER9 dxIB;
	mesh->GetIndexBuffer(&dxIB);

	// get index info
	DWORD nNumIndices = mesh->GetNumFaces() * 3;
	
	// create index buffer
	IndexBuffer::Ptr ib( 
						new IndexBuffer(nNumIndices)
	);

	// get DX vertex data pointer
	void* piTemp = NULL;
	HRESULT hResult = mesh->LockIndexBuffer(0, &piTemp);

	// 
	short* pIndexData = ib->GetIndexPtr();
	memcpy(static_cast<void*>(pIndexData), piTemp, sizeof(short) * nNumIndices);

	mesh->UnlockIndexBuffer();

	// assign IB to mesh
	_Mesh.SetIndexBuffer(ib);

	return true;
}

}//end namespace